-module(output_latex_common).
-export([fill/3, float_to_latex/1, escape/1, list_to_latex/1, float_to_latex/2]).

%fill(S, _, _) -> S;
fill(S, _, N) when length(S) >= N ->
    S;
fill(S, Fill, N) ->
    fill(Fill++S, Fill, N).

list_to_latex([]) ->
    "";
list_to_latex([N|L]) ->
    " & "++integer_to_list(N) ++ list_to_latex(L).

float_to_latex00(X, Decs, Base) ->
    integer_to_list(trunc(X))
    ++"&"
    ++fill(
        integer_to_list(round(Base*(X-trunc(X)))),
        "0",
        Decs).

float_to_latex0(X, Decs, Base) ->
    X1 = round(Base*X)/Base,
    if
        X1 >= 0.0 ->
            float_to_latex00(X1, Decs, Base);
        true ->
            "-"++float_to_latex00(-X1, Decs, Base)
    end.

float_to_latex(X) ->
    float_to_latex(X, 3).

pow10(0, X) -> X;
pow10(N, X) -> pow10(N-1, X*10).

float_to_latex(X, Decimals) ->
    float_to_latex0(X, Decimals, pow10(Decimals, 1)).

escape([]) ->
    "";
escape([95|S]) ->
    "\\_"++escape(S);
escape([C|S]) ->
    [C|escape(S)].
